package com.bsoft.rpc.basic.codec;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyClient {
    private String host;
    private int port;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void sendMsg() {
        // 创建统一的业务处理线程组
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        // 客户端启动类
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                            nioSocketChannel.pipeline()
                                    .addLast(new MsgEncoder())
                                    .addLast(new MsgDecoder())
                                    .addLast(new NettyClientHandler());
                        }
                    });
            // 连接服务端地址和端口
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            // 注册监听器，监听通道连接结果
            channelFuture.addListener(future -> {
                if (channelFuture.isSuccess()) {
                    log.info("connect success to server => {}:{}", host, port);
                }else{
                    log.error("connect failed to server => {}:{}", host, port);
                    channelFuture.cause().printStackTrace();
                    eventLoopGroup.shutdownGracefully();
                }
            });
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅关闭
            eventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyClient nettyClient = new NettyClient("127.0.0.1", 8888);

        // 发送消息
        nettyClient.sendMsg();
    }
}
